package com.tuu.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.io.File;
import java.io.FileInputStream;
import java.security.*;
import java.util.Enumeration;
public class MyRSAUtils {
    // KeyPair is a simple holder for a key pair.
    private static final KeyStore keyStore = initKey();
    //密钥对的别名
    private static final String keyAlias = "test11";
    /**
     * 初始化方法，产生key pair，提供provider和random
     * @return KeyPair instance
     */
    private static KeyStore initKey() {
        try {
            FileInputStream is = new FileInputStream(new File("d:\\hy.keystore"));
            KeyStore keyStore = KeyStore.getInstance("JKS");
            //这里填设置的keystore密码，两个可以不一致
            keyStore.load(is, "mypass".toCharArray());
            //加载别名，这里认为只有一个别名，可以这么取；当有多个别名时，别名要用参数传进来。不然，第二次的会覆盖第一次的
            Enumeration aliasEnum = keyStore.aliases();
            String keyAlias = "test11" ;
            //while (aliasEnum.hasMoreElements()) {
              //  keyAlias = (String) aliasEnum.nextElement();
              //  System.out.println("别名"+keyAlias);
            //}
            return keyStore;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 产生public key
     * @return public key字符串
     */
    public static String generateBase64PublicKey() throws Exception{
        //RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        //加载公钥
        PublicKey publicKey = keyStore.getCertificate(keyAlias).getPublicKey();
        // encodeBase64(): Encodes binary data using the base64
        // algorithm but does not chunk the output.
        // getEncoded():返回key的原始编码形式
        return new String(Base64.encodeBase64(publicKey.getEncoded()));
    }
    /**
     * 解密数据
     * @param string 需要解密的字符串
     * @return 破解之后的字符串
     */
    public static String decryptBase64(String string) {
        // decodeBase64():将Base64数据解码为"八位字节”数据
        return new String(decrypt(Base64.decodeBase64(string)));
    }
    private static byte[] decrypt(byte[] byteArray) {
        try {
            Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
            Security.addProvider(provider);
            // Cipher: 提供加密和解密功能的实例
            // transformation: "algorithm/mode/padding"
            Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", provider);
            //PrivateKey privateKey = keyPair.getPrivate();
            //加载私钥另一写法
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, "mypass".toCharArray());
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // doFinal(): 加密或者解密数据
            byte[] plainText = cipher.doFinal(byteArray);
            return plainText;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}